using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Material_Management;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Material_Management
{
    public class DeleteBomHandler : IRequestHandler<DeleteBomCommand, ApiResult<int>>
    {
        private readonly IRepository<BomModel> bomRepo;

        public DeleteBomHandler(IRepository<BomModel> bomRepo)
        {
            this.bomRepo = bomRepo;
        }

        /// <summary>
        /// 删除BOM
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(DeleteBomCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            // 验证BOM是否存在
            var existingBom = bomRepo.GetAll().Where(a => a.Id == request.Id && !a.IsDel).FirstOrDefault();
            if (existingBom == null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "BOM不存在！";
                return await Task.FromResult(result);
            }

            if (request.CascadeDelete)
            {
                // 级联删除：删除当前BOM及其所有子级BOM
                await DeleteBomAndChildren(request.Id);
                result.Message = "删除成功（包含所有子级）！";
            }
            else
            {
                // 检查是否有子级BOM
                var hasChildren = bomRepo.GetAll().Any(a => a.ParentId == request.Id && !a.IsDel);
                if (hasChildren)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "该BOM存在子级，无法删除！请先删除子级BOM或选择级联删除。";
                    return await Task.FromResult(result);
                }

                // 只删除当前BOM
                existingBom.IsDel = true;
                existingBom.UpdateTime = DateTime.Now;
                await bomRepo.UpdateAsync(existingBom);

                // 检查父级BOM是否还有其他子级，如果没有则更新IsLeaf状态
                if (existingBom.ParentId.HasValue)
                {
                    var parentBom = bomRepo.GetAll().Where(a => a.Id == existingBom.ParentId.Value && !a.IsDel).FirstOrDefault();
                    if (parentBom != null)
                    {
                        var siblingCount = bomRepo.GetAll().Count(a => a.ParentId == existingBom.ParentId.Value && !a.IsDel);
                        if (siblingCount == 0)
                        {
                            parentBom.IsLeaf = true;
                            await bomRepo.UpdateAsync(parentBom);
                        }
                    }
                }

                result.Message = "删除成功！";
            }

            result.Code = StatusCode.Success;
            result.Data = 1;
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 递归删除BOM及其所有子级
        /// </summary>
        /// <param name="bomId"></param>
        private async Task DeleteBomAndChildren(long bomId)
        {
            var bom = bomRepo.GetAll().Where(a => a.Id == bomId && !a.IsDel).FirstOrDefault();
            if (bom == null) return;

            // 获取所有子级BOM
            var children = bomRepo.GetAll().Where(a => a.ParentId == bomId && !a.IsDel).ToList();
            
            // 递归删除子级
            foreach (var child in children)
            {
                await DeleteBomAndChildren(child.Id);
            }

            // 删除当前BOM
            bom.IsDel = true;
            bom.UpdateTime = DateTime.Now;
            await bomRepo.UpdateAsync(bom);

            // 更新父级的IsLeaf状态
            if (bom.ParentId.HasValue)
            {
                var parentBom = bomRepo.GetAll().Where(a => a.Id == bom.ParentId.Value && !a.IsDel).FirstOrDefault();
                if (parentBom != null)
                {
                    var siblingCount = bomRepo.GetAll().Count(a => a.ParentId == bom.ParentId.Value && !a.IsDel);
                    if (siblingCount == 0)
                    {
                        parentBom.IsLeaf = true;
                        await bomRepo.UpdateAsync(parentBom);
                    }
                }
            }
        }
    }
}
